#include <fhegraphics/Window.h>
#include <fhe/core/Registerers.h>
#include <QtGui/QMainWindow>
#include <QtCore/QTimer>

namespace fhe
{
  namespace graphics
  {
    FHE_NODE( fhegraphics, Window );
    FHE_NODE_INTERFACE( fhegraphics, Window, core, IUpdatable );
    FHE_VAR( fhegraphics, Window, title );
    FHE_VAR( fhegraphics, Window, size );
    FHE_VAR( fhegraphics, Window, clearColor );
    FHE_VAR( fhegraphics, Window, fps );
    
    Window::Window()
      : title( "fhe" )
      , size( 800, 600 )
      , clearColor( 1, 1, 1, 1 )
      , fps( 100 )
      , window_( 0 )
    {
    }
    
    Window::~Window()
    {
    }
    
    void Window::update( double t, double dt )
    {
      if ( !window_ )
      {
        window_ = new QMainWindow;
        window_->setWindowTitle( title.c_str() );
        window_->resize( size.x, size.y );

        glWidget_ = new GLWidget( window_, clearColor, this );
        window_->setCentralWidget( glWidget_ );
        
        timer_ = new QTimer( window_ );
        QObject::connect( timer_, SIGNAL( timeout() ), glWidget_, SLOT( updateGL() ) );
        timer_->start( 1000. / fps );
        
        window_->show();
      }
    }
    
    void Window::render()
    {
      publish( "render", (IRenderContext3d*)(&renderContext_) );
    }
  }
}
